package top.sqdpt.pt.statemachine.config;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ConfigurableApplicationContext;
import top.sqdpt.pt.statemachine.factory.PtStateMachineFactory;
import top.sqdpt.pt.statemachine.action.PtSpringStateAction;
import top.sqdpt.pt.statemachine.machine.PtStateMachine;

import java.util.List;
import java.util.Map;

public class PtStateMachineAutoConfiguration {

    private final ConfigurableApplicationContext applicationContext;

    public PtStateMachineAutoConfiguration(ConfigurableApplicationContext applicationContext, List<PtSpringStateAction<?, ?, ?>> ptSpringStateActionList) {
        this.applicationContext = applicationContext;
        PtStateMachineFactory ptStateMachineFactory = new PtStateMachineFactory(ptSpringStateActionList);
        registerBean("ptStateMachineFactory", ptStateMachineFactory);
        Map<Enum<?>, PtStateMachine<?, ?>> stateMachineMap = ptStateMachineFactory.getStateMachineMap();
        stateMachineMap.forEach((machineEnum, ptSpringStateMachine) -> {
            registerBean(machineEnum.name(), ptSpringStateMachine);
        });
    }

    private void registerBean(String beanName, Object bean) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext.getBeanFactory();
        // 检查Bean是否已存在
        if (registry.containsBeanDefinition(beanName)) {
            return;
        }
        // 创建BeanDefinition
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(bean.getClass());
        beanDefinition.setInstanceSupplier(() -> bean);
        // 注册Bean
        registry.registerBeanDefinition(beanName, beanDefinition);
    }


}
